  <template>
  <div class="qa">
    <el-radio-group class="gparent" v-model="position" style="margin-bottom:30px;">
      <el-radio-button label="choice">
        <a class="fulla" href="#/questions/list/choice">选择题</a>
      </el-radio-button>
      <el-radio-button label="essay">
        <a class="fulla" href="#/questions/list/essay">问答题</a>
      </el-radio-button>
      <el-radio-button label="category">
        <a class="fulla" href="#/questions/list/category">面试提技术管理</a>
      </el-radio-button>
    </el-radio-group>

    <div class="edt-tools">
      <el-form :inline="true" :model="search" class="demo-form-inline">
        <el-form-item label="选择技术名字">
          <el-select v-model="search.skillId" filterable placeholder="请选择">
            <el-option v-for="item in skills" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button type="success" @click="dilogadd">添加面试题</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="choices" row-key="id" stripe style="width: 100%">
      <el-table-column type="index" label="序号" width="180"></el-table-column>
      <el-table-column prop="title" label="面试题"></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <i class="move-icon el-icon-rank"></i>
          <el-button size="mini" @click="loadOne(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加修改框 -->
    <el-dialog top="5vh" :title="msg+'问答题'" :visible.sync="skillwd" width="60%">
      <el-form ref="form" label-width="80px">
        <el-form-item label="题目">
          <mavon-editor
            codeStyle="atelier-forest-light"
            :ishljs="true"
            ref="md1"
            @imgAdd="upload1"
            @imgDel="imgDel1"
            v-model="question.title"
          ></mavon-editor>
        </el-form-item>
        <el-form-item label="答案">
          <mavon-editor
            codeStyle="atelier-forest-light"
            :ishljs="true"
            ref="md2"
            @imgAdd="upload2"
            @imgDel="imgDel2"
            v-model="question.answer"
          ></mavon-editor>
        </el-form-item>
        <el-form-item label="所属技术">
          <el-select class="w100" v-model="question.skillId" filterable placeholder="请选择">
            <el-option
              v-for="item in skills"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="skillwd=false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getAllSkill,
  addEssayQuestion,
  modifyEssayQuestion,
  deleteEssayQuestion,
  oneEssayQuestion,
  getEssayQuestion,
  sortEssayQuestion,
  getSkillEssayQuestion
} from "@/api/publish";
const axios = require('axios')
import { getUser } from '@/utils/store'
// draggable 依赖于 Sortable，当npm install vuedraggable时其实就有了 sortablejs
import draggable from "vuedraggable";
import Sortable from "sortablejs";
export default {
  data() {
    return {
      position: "essay",
      skillwd: false,
      question: {
        id: null,
        title: "",
        answer: "",
        skillId: ""
      },
      //题目集合
      choices: [],
      //技术集合
      skills: [],
      msg: "添加",
      handler: 1,
      search: {
        skillId: null
      },
      //上传图片列表
      img_file1: {},
      img_file2: {},
      codeStyle:'monokai-sublime',//主题
      headers:{
        token:null
      }
    };
  },
  mounted() {
    const Authorization = getUser()
    this.headers.token=Authorization.token
    //加载所有技术
    this.loadSkill();
  },
  methods: {
    //加载所有技术点
    async loadSkill() {
      const result = await getAllSkill();
      this.skills = result.data;
      if (this.skills.length > 0 && this.search.skillId == null) {
        this.search.skillId = this.skills[0].id;
      }
      //加载数据
      this.loadData();
    },
    //添加
    dilogadd() {
      this.question = {
        id: null,
        title: "",
        answer: "",
        skillId: ""
      };
      this.msg = "添加";
      this.skillwd = true;
      this.handler = 1;
    },
    //加载所有
    async loadData() {
      const result = await getSkillEssayQuestion(this.search.skillId);
      this.choices = result.data;
      const el = document.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      Sortable.create(el, {
        disabled: false, // 拖拽不可用? false 启用
        ghostClass: "sortable-ghost", //拖拽样式
        animation: 150, // 拖拽延时，效果更好看
        onEnd: e => {
          // 拖拽结束时的触发
          let arr = this.choices; // 获取表数据
          arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理，获取最新的表格数据
          this.$nextTick(function() {
            this.choices = arr;
            let ids = this.choices.map(item => {
              return item.id;
            });
            //调用后台修改排序
            sortEssayQuestion(ids);
          });
        }
      });
    },
    //添加数据
    async save() {
      let data = JSON.parse(JSON.stringify(this.question));
      if (this.handler == 1) {
        const result = await addEssayQuestion(data);
        console.log(result);
        this.skillwd = false;
      } else {
        const result = await modifyEssayQuestion(data);
        console.log(result);
        this.skillwd = false;
      }
      this.search.skillId = data.skillId;
      //重新加载
      this.loadData();
    },
    //加載詳情
    async loadOne(id) {
      this.msg = "編輯";
      const result = await oneEssayQuestion(id);
      this.question = result.data;
      this.skillwd = true;
      this.handler = 2;
    },
    //刪除
    async del(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const result = await deleteEssayQuestion(id);
        //重新加载
        this.loadData();
        this.$message({
          type: "success",
          message: "删除成功!"
        });
      });
    },
    //图片上传
    upload1(pos, file){
      this.img_file1[pos] = file
      var formdata = new FormData()
      formdata.append("image", file)
      const Authorization = getUser()
      axios({
        url: 'http://api-itmentu.secby.cn/api/upload',
        method: 'post',
        data: formdata,
        headers: { 
          'Content-Type': 'multipart/form-data',
          'token':Authorization.token
        },
      }).then((res) => {  //图片上传到服务器返回图片url 链接
        this.$refs.md1.$img2Url(pos, res.data.data);  //通过ref插入到文档中
      });
    },
    upload2(pos, file){
      this.img_file2[pos] = file
      var formdata = new FormData()
      formdata.append("image", file)
      const Authorization = getUser()
      axios({
        url: 'http://api-itmentu.secby.cn/api/upload',
        method: 'post',
        data: formdata,
        headers: { 
          'Content-Type': 'multipart/form-data',
          'token':Authorization.token
        },
      }).then((res) => {  //图片上传到服务器返回图片url 链接
        this.$refs.md2.$img2Url(pos, res.data.data);  //通过ref插入到文档中
      });
    },
    //删除图片
    imgDel1(pos) {
        delete this.img_file1[pos];
    },
    imgDel2(pos) {
        delete this.img_file2[pos];
    }
  }
};
</script>
<style lang="less" scoped>
.edt-tools {
  border-top: 3px solid #ebecf0;
  border-bottom: 3px solid #ebecf0;
  padding-top: 15px;
  padding-bottom: 15px;
}
</style>